<?php
/*
 * 后台激活码控制器
 */
class ActivationkeyController extends BasicController {
    
    private function init(){
        Yaf_Registry::get('tokenPlugin')->checkAuth(true);
    }

    /*
    * 批量生成激活码 Api 
    */
    public function batchAction(){
        //获取所有post传递过来的参数
        $params = $this->getPost();
        
        $num = isset($params['num']) ? $params['num'] : 0;
        $type = isset($params['type']) ? $params['type'] : 0;
        $price = isset($params['price']) ? $params['price'] : 0;
        
        $return['code'] = 0;
        $return['msg'] = '操作成功！';
        $return['data'] = [];
        
        if(!$num || !$type || !$price || !in_array($type, [1, 2, 3, 4])){//无效的提交参数
            $return['code'] = 1;
            $return['msg'] = '参数错误';
            
            echo json_encode($return);
            return false;
        }
        
        $ActivationkeyModel = Helper::load('Activationkey');
        
        $okNum = 0;
        $keyArr = [];
        //循环生成激活码
        for($i =0; $i < $num; $i++){
            $key = build_activationkey();
            
            $data = [
                'a_key'     => $key,
                'a_type'    => $type,
                'a_price'   => $price,
                'ctime'     => CUR_TIMESTAMP,
                'mtime'     => CUR_TIMESTAMP
            ];
            
            $r = $ActivationkeyModel->Insert($data);
            if($r){//生成成功
                $okNum += 1;
                $keyArr[] = $key;
            }
        }
        
        if(!$okNum){//全部失败
            $return['code'] = 2;
            $return['msg'] = '数据库错误，操作失败';
            
            echo json_encode($return);
            return false;
        }
        
        if($okNum != $num){//数量不一致
            $return['code'] = 3;
            $return['msg'] = '部分操作失败';
            $return['data']['keys'] = $keyArr;
            
            echo json_encode($return);
            return false;
        }
        
        //走到这里为成功
        $return['data']['keys'] = $keyArr;
        
        echo json_encode($return);
        return false;
    }
    
}